<template>
  <div class="edit-page-wrap">
    <Head title="基本信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="edit-form-wrap"
        >
          <el-form-item label="模板名称" prop="templateName">
            <el-input
              v-model.trim="ruleForm.templateName"
              placeholder="请输入模板名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="协议版本" prop="protocolVersion">
            <qc-select
              v-if="!id"
              :value="ruleForm.protocolVersion"
              :options="optionsS.version"
              placeholder="请选择协议版本"
              @change="handleVersion"
            >
            </qc-select>
            <div v-else>{{ getVersionName() }}</div>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head v-if="ruleForm.protocolVersion" title="充电单价">
      <template #tip>
        <div class="head-tip left-8" v-if="ruleForm.protocolVersion === '1'">
          <div class="icon"></div>
          温馨提示：最多支持拆分5个时段
        </div>
        <div class="head-tip left-8" v-if="ruleForm.protocolVersion === '100'">
          <div class="icon"></div>
          温馨提示：价格类别最多只支持4组，价格时段最多支持拆分48个时段
        </div>
      </template>
      <template #content>
        <PriceUdp
          ref="udpRef"
          :protocolVersion="ruleForm.protocolVersion"
          v-if="ruleForm.protocolVersion === '1'"
        ></PriceUdp>
        <PriceTcp
          ref="tcpRef"
          :protocolVersion="ruleForm.protocolVersion"
          v-if="ruleForm.protocolVersion === '100'"
        ></PriceTcp>
      </template>
    </Head>

    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import Head from '@/components/head/index.vue';
import PriceUdp from '../components/priceUdp.vue';
import PriceTcp from '../components/priceTcp.vue';
import {
  addCostTemplate,
  queryCostTemplate,
  updateCostTemplate,
} from '@/service/apis/pile';
import { queryDicByParent } from '@/service/apis/api';

const router = useRouter();
const route = useRoute();
const {
  query: { id, isCopy },
} = route;
const ruleFormRef = ref<FormInstance>();
const udpRef = ref();
const tcpRef = ref();

let optionsS = reactive({
  version: [] as any,
});

queryDicByParent({
  listDtos: ['protocolVersion'],
}).then((res: any) => {
  if (res) {
    optionsS.version = [...res.protocolVersion];
  }
});

let ruleForm = reactive({
  id: id,
  templateName: '',
  protocolVersion: undefined as unknown,
  costTemplateUdpDTOList: [] as any,
  costTemplateTcpPriceTypeDTOList: [] as any,
  costTemplateTcpPriceSetDTOList: [] as any,
});
const rules = reactive<FormRules>({
  templateName: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
  ],
  protocolVersion: [
    { required: true, message: '请选择协议版本', trigger: 'blur' },
  ],
});

if (id) {
  queryCostTemplate({ id: id }).then((res: any) => {
    if (res) {
      console.log('res---', res);
      ruleForm.templateName = res.templateName;
      ruleForm.protocolVersion = res.protocolVersion;

      nextTick(() => {
        if (ruleForm.protocolVersion === '1') {
          ruleForm.costTemplateUdpDTOList = res.costTemplateUdpList;
          udpRef?.value?.setData(res.costTemplateUdpList);
        } else if (ruleForm.protocolVersion === '100') {
          ruleForm.costTemplateTcpPriceTypeDTOList =
            res.costTemplateTcpPriceTypeList;
          ruleForm.costTemplateTcpPriceSetDTOList =
            res.costTemplateTcpPriceSetList;
          tcpRef?.value?.setData(
            res.costTemplateTcpPriceTypeList,
            res.costTemplateTcpPriceSetList
          );
        }
      });
    }
  });
}

const getVersionName = () => {
  if (ruleForm.protocolVersion && optionsS.version?.length > 0) {
    const obj = optionsS.version.find(
      (item: any) => item.value === ruleForm.protocolVersion
    );
    return obj.label;
  }
  return '--';
};

const handleVersion = (e: any) => {
  ruleForm.protocolVersion = e;
};

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  if (ruleForm.protocolVersion === '1' && !udpRef.value) return;
  if (ruleForm.protocolVersion === '100' && !tcpRef.value) return;
  let comData = [] as any;
  try {
    if (ruleForm.protocolVersion === '1') {
      comData = await Promise.all([
        ruleFormRef.value.validate(),
        udpRef?.value?.getData(),
      ]);
      if (!comData[1]) return;
      ruleForm.costTemplateUdpDTOList = comData[1];
    } else if (ruleForm.protocolVersion === '100') {
      comData = await Promise.all([
        ruleFormRef.value.validate(),
        tcpRef?.value?.getData(),
      ]);
      if (!comData[1]) return;
      ruleForm.costTemplateTcpPriceTypeDTOList = comData[1].type;
      ruleForm.costTemplateTcpPriceSetDTOList = comData[1].time;
    } else {
      await Promise.all([ruleFormRef.value.validate()]);
    }
  } catch (fields: any) {
    for (const key in ruleForm) {
      if (fields[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  console.log(ruleForm);
  if (id && !isCopy) {
    updateCostTemplate(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    ruleForm.id = '';
    addCostTemplate(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>